mrjs = {
  __worker: null,

  listeners: [],

  notifyListeners: function(obj) {
    for (var i = 0; i < mrjs.listeners.length; i++) {
      mrjs.listeners[i](obj);
    }
  }, 

  stop: function() {
    mrjs.__worker.terminate();
    clearTimeout(mrjs.timer);
  },

  start: function(opt_workerUrl) {
    // GET the next script
    mrjs.__worker = new Worker(opt_workerUrl || '/serve');

    // terminate the worker in 10s
    mrjs.timer = setTimeout(mrjs.stop, 10000);

    mrjs.__worker.addEventListener('message', function(e) {
      if ('log' in e.data) {
        console.log(e.data.log);
        return;
      }
      // If the Worker says it's completed all inputs for a task,
      // stop this worker and start a new one.
      if ('newTask' in e.data) {
        mrjs.stop();
        setTimeout('mrjs.start()', 500);
        return;
      }
      // Feed the meter another 10s
      clearTimeout(mrjs.timer);
      mrjs.timer = setTimeout(mrjs.stop, 10000);

      mrjs.notifyListeners(e.data);
    });

    mrjs.__worker.onerror = function(event) {
      mrjs.notifyListeners({error:true});
    };

    // start the worker
    mrjs.__worker.postMessage();
  }
};